package com.example.springbootmybatisredis.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootmybatisredis.entity.BankInfo;
import com.example.springbootmybatisredis.entity.ESInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test;
import org.elasticsearch.common.text.Text;
import org.springframework.data.annotation.CreatedDate;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:ElasticSearchController
 * Package:com.example.springbootmybatisredis.controller
 * Description:
 *
 * @date:2021/6/15 16:34
 * @author:xy
 */
public class ElasticSearchController {


    private RestHighLevelClient client = null;
 /**
 * Description:
 * date: 2021/6/16 10:01
 * @author: xiyang
 * 获取客户端client
 */

   @Before
    public void prepare() throws IOException {
       HttpHost httpHostOne = new HttpHost("127.0.0.1", 9200, "http");
       RestClientBuilder builder = RestClient.builder(httpHostOne);
        client = new RestHighLevelClient(builder);


   }

    private static Settings getDefaultSetting(){
        return Settings.builder()
                .put("index.refresh_interval", "60s")
                .put("index.number_of_shards", "3")
                .put("index.number_of_replicas", "1")
                .build();

    }


    /**
     * 创建索引 和 映射
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        String indexName = "xy_test3";
        IndicesClient indicesClient = client.indices();
        //        mapping是针对索引，所以先添加索引,当然也可以在添加索引的时候就设置
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName).settings(getDefaultSetting());
        indicesClient.create(createIndexRequest, RequestOptions.DEFAULT);

        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("properties")
                .startObject("gid").field("type", "keyword").field("doc_values",false).endObject()
                .startObject("serverId").field("type", "integer").endObject()
                .endObject()
                .endObject();
        PutMappingRequest putMappingRequest = new PutMappingRequest(indexName).source(mapping);
        indicesClient.putMapping(putMappingRequest, RequestOptions.DEFAULT);
        client.close();
    }

    /**
     * 删除索引
     */
    //删除索引库
    @Test
    public void testDeleteIndex() throws IOException {
        //删除索引请求对象
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xy2");
        //删除索引
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged =    delete.isAcknowledged();
        //删除索引响应结果
        System.out.println(acknowledged);
    }

    /**
     * 插入文档
     */
    @Test
    public void testAddDocument() throws IOException {
        //准备json数据
//        Map<String, Object> jsonMap = new HashMap<>();
//        jsonMap.put("name", "11spring cloud实战");
//        jsonMap.put("description", "搜索工作其实很快乐");
//        jsonMap.put("studymodel", "201001");
//        jsonMap.put("price", 5.6f);

        ESInfo esInfo = new ESInfo(1L,"搜搜使我快乐-id_1",new Date());

        // 建立文档
        //索引请求对象
        IndexRequest indexRequest = new IndexRequest("xy_test1" ).id(esInfo.getId().toString());
         //7.0以后没有type
        // indexRequest.type();
        //指定索引文档内容
        //  indexRequest.source("esInfo3",66556666);
          indexRequest.source(esInfo,XContentType.JSON);
        //索引响应对象
        IndexResponse index = client.index(indexRequest,RequestOptions.DEFAULT);

        //获取响应结果
        DocWriteResponse.Result result = index.getResult();
        System.out.println(result);


    }

    /**
     * 查询文档  根据ID查询
     */
    @Test
    public void getDocumentById() throws IOException {
        GetRequest getRequest = new GetRequest("xy_test1", "1");

        GetResponse response = client.get(getRequest,RequestOptions.DEFAULT);

        boolean exists = response.isExists();

        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        System.out.println("sourceAsMap:"+sourceAsMap);

    }

    /**
     * 更新文档
     */
    @Test
    public void updateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("xy", "doc", "11");

        Map<String, String> map = new HashMap<>();
        map.put("name", "spring cloud实战222");
        updateRequest.doc(map);

        UpdateResponse update = client.update(updateRequest,RequestOptions.DEFAULT);

        RestStatus status = update.status();

        System.out.println(status);
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteDocument() throws IOException {
        String id = "AXIDNJoC19Z06cvw7_Gv";
        DeleteRequest deleteRequest = new DeleteRequest("xy2", "doc", id);

        DeleteResponse delete = client.delete(deleteRequest,RequestOptions.DEFAULT);

        System.out.println(delete.status());
    }

    /**
     * 搜索管理  查询所有文档
     */
    @Test
    public void testSearchAll() throws IOException {

        SearchRequest searchRequest = new SearchRequest("xy_test1");
       // searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //source源字段过虑
      //  searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();

        System.out.println("total=" + totalHits);

        SearchHit[] searchHits = hits.getHits();
      //  SearchHit[] hits1 = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String index = searchHit.getIndex();
            System.out.println("index=" + index);
            String id = searchHit.getId();
            System.out.println("id=" + id);
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            //String articleId = String.valueOf( sourceAsMap.get( "id" ) );
//            String title = (String) sourceAsMap.get("title");
//            String createData = (String) sourceAsMap.get("createdata");
            //System.out.println("articleId="+articleId);
//            System.out.println("title=" + title);
//            System.out.println("createdata=" + createData);
        }


    }

    /**
     * 搜索管理  分页查询
     */
    @Test
    public void testSearchByPage() throws IOException {
        //设置要查询的索引 和 type
        SearchRequest searchRequest = new SearchRequest("xy");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //分页查询，设置起始下标，从0开始
        searchSourceBuilder.from(0);
        //每页显示个数
        searchSourceBuilder.size(2);
        //source源字段过虑
        //searchSourceBuilder.fetchSource(new String[]{"title","id","content"},new String[]{}  );
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println(totalHits);
        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }


    /**
     * 搜索管理  Term Query精确查找 ，在搜索时会整体匹配关键字，不再将关键字分词 ，
     * 下面的语句：查询title 包含 spring 的文档
     */
    @Test
    public void testSearchTerm() throws IOException {
        //创建查询，设置索引
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("name", "spring"));
        //source源字段过虑
        //searchSourceBuilder.fetchSource(new String[]{"title","id","content"},new String[]{});
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

    /**
     * 搜索管理 根据ID查询
     */
    @Test
    public void testSearchByID() throws IOException {
        //创建查询，设置索引
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        String[] ids = {"11", "12"};
        List<String> stringList = Arrays.asList(ids);
        searchSourceBuilder.query(QueryBuilders.termsQuery("_id", stringList));
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

    /**
     * 搜索管理 match query 先分词后查找
     */
    @Test
    public void testSearchMatch() throws IOException {
        //创建查询，设置索引
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //匹配关键字
        searchSourceBuilder.query(QueryBuilders.matchQuery("name", "spring开发").operator(Operator.OR));
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }


    /**
     * 搜索管理 match query 先分词后查找 minimum_should_match  （如果实现三个词至少有两个词匹配如何实现）
     */
    @Test
    public void testSearchMatchMinimnum() throws IOException {
        //创建查询，设置索引
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //匹配关键字
        searchSourceBuilder.query(QueryBuilders.matchQuery("name", "spring开发").minimumShouldMatch("60%"));
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }


    /**
     * 搜索管理 同时搜索多个Field
     */
    @Test
    public void testSearchMultiMatch() throws IOException {
        //创建查询，设置索引
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //匹配关键字
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("Boot 开发", "name", "description")
                .minimumShouldMatch("50%");
        multiMatchQueryBuilder.field("name", 10);//提升boost 表示权重提升10倍

        searchSourceBuilder.query(multiMatchQueryBuilder);
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

    /**
     * 搜索管理 布尔查询
     */
    @Test
    public void testSearchBoolean() throws IOException {
        //创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
        //创建搜索源配置对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        //multiQuery
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("Boot 开发", "name", "description")
                .minimumShouldMatch("50%");
        multiMatchQueryBuilder.field("name", 10);//提升boost 表示权重提升10倍
        //TermQuery
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("studymodel", "201001");
        // 布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(multiMatchQueryBuilder);
        boolQueryBuilder.must(termQueryBuilder);
        //设置布尔查询对象
        searchSourceBuilder.query(boolQueryBuilder);
        //设置搜索源配置
        searchRequest.source(searchSourceBuilder);
        //搜索
        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }


    /**
     * 搜索管理 过滤器
     */
    @Test
    public void testSearchFilter() throws IOException {
        //创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest("xy");
        //设置type
        searchRequest.types("doc");
      //  创建搜索源配置对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});
        //multiQuery 多field查询
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("Boot 开发", "name", "description")
                .minimumShouldMatch("50%");
        multiMatchQueryBuilder.field("name", 10);//提升boost 表示权重提升10倍
        //多Field查询，添加到搜索源配置对象中
        searchSourceBuilder.query(multiMatchQueryBuilder);

        //TermQuery
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("studymodel", "201001");
        //Term查询，添加到搜索源配置对象中
        searchSourceBuilder.query(termQueryBuilder);

        // 布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(searchSourceBuilder.query());

        //过虑
        boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel", "201001"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(5).lte(100));

        //设置布尔查询对象
        searchSourceBuilder.query(boolQueryBuilder);
        //设置搜索源配置
        searchRequest.source(searchSourceBuilder);
        //搜索
        SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);

        for (SearchHit searchHit : hits.getHits()) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

    /**
     * 排序
     *
     * @throws IOException
     */
    @Test
    public void testSort() throws IOException {
        SearchRequest searchRequest = new SearchRequest("xy");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "price", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //过虑
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
        // 排序
        searchSourceBuilder.sort(new FieldSortBuilder("studymodel").order(SortOrder.DESC));
        searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC));
        //搜索
        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }

    }

    /**
     * 高亮显示
     *
     * @throws IOException
     */
    @Test
    public void testHighlight() throws IOException {
        SearchRequest searchRequest = new SearchRequest("xy");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //source源字段过虑
        searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "price", "description"}, new String[]{});
        searchRequest.source(searchSourceBuilder);
        //匹配关键字
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("实战", "name", "description");
        searchSourceBuilder.query(multiMatchQueryBuilder);
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(searchSourceBuilder.query());
        //过虑
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
        //排序
        searchSourceBuilder.sort(new FieldSortBuilder("studymodel").order(SortOrder.DESC));
        searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC));
        //高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<tag>");//设置前缀
        highlightBuilder.postTags("</tag>");//设置后缀
        // 设置高亮字段
        highlightBuilder.fields().add(new HighlightBuilder.Field("name"));
        //highlightBuilder.fields().add(new HighlightBuilder.Field("description"));
        searchSourceBuilder.highlighter(highlightBuilder);

        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //名称
            String name = (String) sourceAsMap.get("name");
            //取出高亮字段内容
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null) {
                HighlightField nameField = highlightFields.get("name");
                if (nameField != null) {
                    Text[] fragments = nameField.getFragments();
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Text str : fragments) {
                        stringBuffer.append(str.string());
                    }
                    name = stringBuffer.toString();
                }
            }
            System.out.println("高亮==" + name);

            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

}
